﻿using ERP.ERPSystem.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Team.ProductionSystem;
using ERP.Team.WarehouseManagement;
using ERP.ERPSystem.ProductionSystem.Dto;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GetProductionWorkOrderMainDto = ERP.ERPSystem.WarehouseManagement.Dto.GetProductionWorkOrderMainDto;

namespace ERP.Web.Controllers.WarehouseManagement
{
    /// <summary>
    /// 仓储管理-xzc
    /// </summary>
    [Route("[controller]/[action]")]
    public class WarehousingsController : Controller
    {
        private readonly IOutsourcedServices _ioutsourcedservices;
        private readonly ISalesReturnServices _isalesreturnservices;
        private readonly IInventoryHandServices _inventoryhandservices;
        public WarehousingsController(IOutsourcedServices ioutsourcedservices, ISalesReturnServices isalesreturnservices, IInventoryHandServices inventoryhandservices)
        {
            _ioutsourcedservices = ioutsourcedservices;
            _isalesreturnservices = isalesreturnservices;
            _inventoryhandservices = inventoryhandservices;
        }

        /// <summary>
        /// 库存信息-库存现有量视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult InventoryOnHandView()
        {
            return View();
        }




        /// <summary>
        /// 销售退货视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SalesReturnsView()
        {
            return View();
        }
        /// <summary>
        /// 客户视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ShowUserView()
        {
            return View();
        }
        /// <summary>
        /// 新增销售退货视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddSalesReturnsView()
        {
            return View();
        }
        /// <summary>
        /// 更新销售退货视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult UpdateSalesReturnsView()
        {
            return View();
        }


        /// <summary>
        /// 外协发料视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult OutsourcedView()
        {
            return View();
        }
        /// <summary>
        /// 新增外协发料视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddOutsourcedView()
        {
            return View();
        }
        /// <summary>
        /// 更新外协发料视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult UpdateOutsourcedView()
        {
            return View();
        }
        /// <summary>
        /// 外协工单视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult WorkOrderView()
        {
            return View();
        }
        #region 库存现有量方法
        /// <summary>
        /// 新增库存现有量 
        /// </summary>
        /// <param name="inventoryDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddInventory(InventoryDto inventoryDto)
        {
            var i = await _inventoryhandservices.AddInventory(inventoryDto);
            return i;
        }
        /// <summary>
        /// 更新库存现有量 
        /// </summary>
        /// <param name="inventoryDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpateInventory(InventoryDto inventoryDto)
        {
            var i = await _inventoryhandservices.UpateInventory(inventoryDto);
            return i;
        }
        /// <summary>
        /// 删除库存现有量 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task DeleteInventory(int id)
        {
            await _inventoryhandservices.DeleteInventory(id);
        }
        /// <summary>
        /// 查询库存现有量 
        /// </summary>
        /// <param name="getinventorysdto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInventory([FromQuery] GetInventorysDto getinventorysdto)
        {
            try
            {
                var inventoryData = await _inventoryhandservices.GetInventory(getinventorysdto ?? new GetInventorysDto());
                return Json(new { success = true, data = inventoryData });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取物料分类树形结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMaterialTypeTree()
        {
            try
            {
                var treeData = await _inventoryhandservices.GetMaterialTypeTree();
                return Json(new { success = true, data = treeData });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 根据物料分类ID查询库存数据
        /// </summary>
        /// <param name="materialTypeId"></param>
        /// <param name="getinventorysdto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInventoryByMaterialType(int? materialTypeId, [FromQuery] GetInventorysDto getinventorysdto)
        {
            try
            {
                var inventoryData = await _inventoryhandservices.GetInventoryByMaterialType(materialTypeId, getinventorysdto ?? new GetInventorysDto());
                return Json(new { success = true, data = inventoryData });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 根据物料分类ID直接匹配ProductItem查询库存数据
        /// </summary>
        /// <param name="materialTypeId"></param>
        /// <param name="getinventorysdto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInventoryByProductItem(int materialTypeId, [FromQuery] GetInventorysDto getinventorysdto)
        {
            try
            {
                var inventoryData = await _inventoryhandservices.GetInventoryByProductItem(materialTypeId, getinventorysdto ?? new GetInventorysDto());
                return Json(new { success = true, data = inventoryData });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取库存数据和物料分类的调试信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInventoryDebugInfo()
        {
            try
            {
                var debugInfo = await _inventoryhandservices.GetInventoryDebugInfo();
                return Json(new { success = true, data = debugInfo });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        #endregion

        #region 销售退货方法
        /// <summary>
        /// 新增销售退货
        /// </summary>
        /// <param name="salesrtrunsdto"></param>
        /// <returns></returns>
        [HttpPost]  
        public async Task<int> AddSalesReturns(SalesReturnsDto salesrtrunsdto)
        {
            var i = await _isalesreturnservices.AddSalesReturns(salesrtrunsdto);
            return i;
        }
        /// <summary>
        /// 更新销售退货
        /// </summary>
        /// <param name="salesrtrunsdto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateSalesReturns(SalesReturnsDto salesrtrunsdto)
        {
            var i = await _isalesreturnservices.UpdateSalesReturns(salesrtrunsdto);
            return i;
        }
        /// <summary>
        /// 删除销售退货
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]  
        public async Task<IActionResult> DeleteSalesReturns(int id)
        {
            try
            {
                await _isalesreturnservices.DeleteSalesReturns(id);
                return Json(new { success = true, message = "删除成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "删除失败: " + ex.Message });
            }
        }
        /// <summary>
        /// 查询销售退货
        /// </summary>
        /// <param name="getalesReturndto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<SalesReturns>> GetSalesReturns(GetSalesReturnsDto getalesReturndto)
        {
            var i = await _isalesreturnservices.GetSalesReturns(getalesReturndto);
            return i;
        }
        /// <summary>
        /// 通过主键id查询到相对应销售退货
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<SalesReturns>> FindSalesReturns(int id)
        {
            var i = await _isalesreturnservices.FindSalesReturns(id);
            return i;
        }
        /// <summary>
        /// 批量删除销售退货
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> BatchDeleteSalesReturns([FromBody] List<int> ids)
        {
            try
            {
                if (ids == null || ids.Count == 0)
                {
                    return Json(new { success = false, message = "请选择要删除的记录" });
                }

                var deletedCount = await _isalesreturnservices.BatchDeleteSalesReturns(ids);
                
                if (deletedCount > 0)
                {
                    return Json(new { success = true, message = $"成功删除 {deletedCount} 条记录" });
                }
                else
                {
                    return Json(new { success = false, message = "删除失败" });
                }
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "删除过程中发生错误: " + ex.Message });
            }
        }
        #endregion

        #region 外协发料方法
        /// <summary>
        /// 新增外协发料
        /// </summary>
        /// <param name="issuingmaterialsdto"></param>
        /// <returns></returns>
        [HttpPost]  
        public async Task<int> AddIssuingMaterials(IssuingMaterialsDto issuingmaterialsdto)
        {
            var i = await _ioutsourcedservices.AddIssuingMaterials(issuingmaterialsdto);
            return i;
        }
        /// <summary>
        /// 更新外协发料
        /// </summary>
        /// <param name="issuingmaterialsdto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateIssuingMaterials(IssuingMaterialsDto issuingmaterialsdto)
        {
            var i = await _ioutsourcedservices.UpdateIssuingMaterials(issuingmaterialsdto);
            return i;
        }
        /// <summary>
        /// 删除外协发料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task DeleteIssuingMaterials(int id)
        {
            await _ioutsourcedservices.DeleteIssuingMaterials(id);
        }
        /// <summary>
        /// 查询外协发料
        /// </summary>
        /// <param name="getissuingmaterialsdto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<IssuingMaterials>> GetIssuingMaterials(GetIssuingMaterialsDto getissuingmaterialsdto)
        {
            var i = await _ioutsourcedservices.GetIssuingMaterials(getissuingmaterialsdto);
            return i;
        }
        /// <summary>
        /// 查询外协工单数据
        /// </summary>
        /// <param name="getproductionworkordermaindto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<ProductionWorkOrderMain>> GetProductionWorkOrderMain(GetProductionWorkOrderMainDto getproductionworkordermaindto)
        {
            var i = await _ioutsourcedservices.GetProductionWorkOrderMain(getproductionworkordermaindto);
            return i;
        }
        /// <summary>
        /// 通过id查询到相应的外协发料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<IssuingMaterials>> FindIssuingMaterials(int id)
        {
            var i = await _ioutsourcedservices.FindIssuingMaterials(id);
            return i;
        }
        /// <summary>
        /// 批量删除外协发料
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDeleteIssuingMaterials()
        {
            try
            {
                // 从表单数据中读取ids参数
                string idsString = Request.Form["ids"];
                
                if (string.IsNullOrEmpty(idsString))
                {
                    return Json(0);
                }
                
                // 解析ID字符串为整数列表
                List<int> idList = idsString.Split(',', StringSplitOptions.RemoveEmptyEntries)
                                           .Select(id => int.Parse(id.Trim()))
                                           .ToList();
                
                if (idList.Count == 0)
                {
                    return Json(0);
                }
                
                // 调用批量删除服务
                var result = await _ioutsourcedservices.BatchDeleteIssuingMaterials(idList);
                return Json(result);
            }
            catch (Exception ex)
            {
                // 记录异常信息（在实际项目中应该使用日志框架）
                System.Diagnostics.Debug.WriteLine($"批量删除失败: {ex.Message}");
                return Json(0);
            }
        }
        #endregion
    }
}
